<template>
  <div style="padding-bottom: 20px;">
    <div class="df">
      <h2>结算申请单 <span style="margin-left: 20px;color: #200281;">{{ Send.billNo }}</span></h2>
    </div>
    <div style="width: 100%;border-bottom: 1px solid #000;">
      <h2><i class="el-icon-document"></i><span style="margin-left: 20px;font-weight: normal;">药品信息</span></h2>
    </div>
    <el-row :span="6" class="df" style="margin: 20px 0;">
      <el-col :span="6" style="display: flex;justify-content: center;align-items: center;margin-right: 60px;">
        <span style="display: block;width: 80px;">医药机构:</span>
        <el-input size="mini" v-if="Send.instName" v-model="Send.instName" disabled></el-input>
        <el-select v-else v-model="value3" size="mini" placeholder="请选择" @change="instChange" :clearable="true">

          <el-option v-for="item in form" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-button @click="toAdd" size="small" type="primary"><i class="el-icon-plus"></i>添加结算药品</el-button>
    </el-row>
    <el-alert size="mini" show-icon
      style="background-color: #d3deee;border: 1px solid #2558ac; color: #2558ac;font-size: 14px;">
      药品种类总数 <span class="number" style="color: #2558ac;font-weight: 700;">{{ num }}</span> 项，总金额<span class="number" style="color: #2558ac;font-weight: 700;">{{ priceSum }}</span>元。
    </el-alert>
    <el-table :data="tableData2" style="width: 100%;margin-top: 20px;" size="mini">
      <el-table-column prop="batchName" label="集采批次" width="180">
      </el-table-column>
      <el-table-column prop="medicineNo" label="流水号" width="180">
      </el-table-column>
      <el-table-column prop="medicineName" label="通用名" width="180">
      </el-table-column>
      <el-table-column prop="categoryName" label="品种名称">
      </el-table-column>
      <el-table-column label="采购数量">
        <template slot-scope="scope">
          {{ scope.row.purchaseAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="purchasePrice" label="采购价(元)">
      </el-table-column>
      <el-table-column prop="purchaseFee" label="采购金额(元)">
      </el-table-column>
      <el-table-column label="发票号">
        <template slot-scope="scope">
          <el-input v-if="scope.row.id == tableData[0].id" v-model="scope.row.invoiceNo"></el-input>
          <el-select v-else
            v-model="scope.row.invoiceNo" @blur="productSelect" filterable placeholder="请输入" allow-create :clearable="true">
            <el-option v-for="item in options" :key="item" :label="item.label" :value="item.value1"></el-option>

          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="发票附件">
        <template slot-scope="scope">

          <div v-if="scope.row.invoiceNo === 0">同上</div>

          <el-upload v-else-if="scope.row.invoiceFile == null || scope.row.invoiceFile == '' || scope.row.invoiceNo == ''"
            :action="fileUrl()" v-model="scope.row.invoiceFile" :on-success="(response, row) => {
              return handleUploadSuccess(response, row, scope.row);
            }">
            <el-button size="small" type="primary">上传文件</el-button>
          </el-upload>
          <a :href="scope.row.invoiceFile" v-else-if="scope.row.invoiceFile !== '' && scope.row.invoiceNo !== 0"><i class="el-icon-paperclip"></i>发票{{
            scope.row.invoiceNo }}.pdf</a>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-popconfirm style="margin: 0 10px;" :title="tableData2.length == 1 ? '这是最后一条数据了,是否要删除' : '请确认是否删除'"
            @confirm="handleDelete(scope.row.id)" class="ml10">
            <el-button type="primary" slot="reference" size="mini">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin: 20px 0;margin-left: 60%;">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="SIZE"
        :page-sizes="[20, 30, 40, 50]">
      </el-pagination>
    </div>
    <el-dialog v-if="dialogVisible" :width="dialogScreen ? '' : '1500px'" :visible.sync="dialogVisible" append-to-body>
      <addBill :instName="instData" :add="addData" :flag2="dialogVisible" @chooseData="changeData" @changeTwo="changeDia">
      </addBill>
    </el-dialog>
    <el-button v-if="userInfo.role_name.includes('distribution')" class="width" type="primary"
      style="margin-left:45%;margin-right: 60px;" plain @click="Staging(true)">暂存</el-button>
    <el-popconfirm style="margin: 0 10px;" title="该操作将提交结算申请给医药机构审核，请确认。" class="ml10" @confirm="handleTop(false)">
      <el-button class="width" style="margin-right:60px" slot="reference" type="primary" size="small">提交</el-button>
    </el-popconfirm>

    <el-button class="width" size="small" @click="hide">取消</el-button>
  </div>
</template>
  
<script>
import {  getUpdata, remove, getNewDetail, getSeDetail, Fathremove } from "../../api/businessTwo/orderDetail"
import { mapGetters } from 'vuex'
import addBill from "../../components/orderDetail/addBill.vue"
import { getToken } from '@/util/auth';
export default {
  components: {
    addBill,
  },
  props: {
    Send: {
      type: Object
    },
    flag: {
      type: Boolean
    }
  },
  data() {
    return {
      options: [{ label: "同上", value: '', value1: 0 }],
      instData: {},
      dialogScreen: false,
      cities: [],
      dialogVisible: false,
      addData: {},
      pageSize: 20,
      tableData1: [],
      SIZE: 0,
      form1: null,
      value2: null,
      value3: '',
      value4: '',
      num: 0,
      priceSum: 0,
      currentPage: 1,
      value: '',
      uploadUrl: "",
      form: [
      ],
      tableData: [],
      tableData2: []
    }
  },
  created() {
    this.getList()
    console.log(this.Send);
    this.number()
    this.changeAdd()
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    value(val) {
      this.inputValue = val;
    }
  },
  methods: {
    changeAdd() {
      this.instData.label = this.Send.instName
      this.instData.vlaue = this.Send.instId
    },
    toAdd() {
      if (this.Send.length!=0) {
      
        this.dialogVisible = !this.dialogVisible
      } else if (this.value3 !== '') {
 
        this.dialogVisible = !this.dialogVisible
      }
      else {
  
        this.$message.error(`请先选择医药机构。`);
      }

    },
    productSelect(e) {
      let value = e.target.value; // 输入框值
      if (value) { // 你输入才有这个值 不为空，如果你下拉框选择的话 这个值为空
        this.value4 = value
        /*  this.options[0].value=value */
      }
      console.log(this.options);
      console.log(e, this.tableData);



    },
    handleUploadSuccess(response, row, rowInfo) {
      // 处理上传成功后的响应数据
      console.log(response, row, rowInfo);
      console.log("上传成功！", response);
      // 保存返回结果到某个变量
      rowInfo.invoiceFile = response.data.name;
      console.log(row);
    },
    async getForm() {
      let res = await getSeDetail()
      console.log(res);
      let arr = []
      if (res.data.code == 200) {
        res.data.data.map((v) => {
          arr.push({ value: v.instId, label: v.instName })
        })
        arr.forEach((item) => {
          if (!this.form.some(m => m.value === item.value)) {
            this.form.push(item);
          }
          return this.form;
        })
      }

    },
    changeTabel() {
      this.tableData2 = this.tableData.slice((this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize)
    },
    async getList() {
      this.getForm()
      if (this.Send.batchId == "" || this.Send.batchId == null) {
        console.log(this.SIZE);
      } else {
        let res = await getNewDetail({
          current: this.currentPage,
          size: this.pageSize,
          billNo: this.Send.billNo,
          instName: this.instName
        })
        this.tableData = this.tableData1.concat(res.data.data)
        console.log(res);
        this.SIZE = this.tableData.length
        this.number()
        this.changeTabel()
      }

    },
    handleTop(data) {
  let arr=[]
  console.log(this.tableData);
      this.tableData.some((v, i) => {
        if(!v.deliveryCompanyName){
          v.deliveryCompanyName=v.companyName
          v.deliveryCompanyId=v.companyId
        }
         console.log(v.deliveryCompanyName,v.deliveryCompanyNo);
        if (this.tableData2[0].invoiceNo == 0 || this.tableData2[0].invoiceFile == "" || this.tableData2[0].invoiceNo == null || this.tableData2[0].invoiceFile == null) {
        
        } else {
          console.log(v, i);
          if (v.invoiceNo == 0) {
            v.invoiceNo = this.tableData[i - 1].invoiceNo
            v.invoiceFile = this.tableData[i - 1].invoiceFile

          }
        }
        
        arr.push({
          id:v.id ||null,
          orderId:v.orderId,
          batchName:v.batchName,
            batchId:v.batchId,
instId:v.instId,
instName:v.instName,
instNo:v.instNo,
medicineNo:v.medicineNo,
medicineName:v.medicineName,
categoryName:v.categoryName,
shotType:v.shotType,
specification:v.specification,
pack:v.pack,
purchaseAmount:v.purchaseAmount,
purchasePrice:v.purchasePrice,
purchaseFee:v.purchaseFee,
companyId:v.deliveryCompanyId,
companyName:v.deliveryCompanyName,
invoiceId:v.invoiceId,
invoiceNo:v.invoiceNo,
invoiceFile:v.invoiceFile,
instUser:v.instUser,
areaUser:v.areaUser,
paymentFile:v.paymentFile
          })
      })
      console.log(this.tableData);
      let c = this.tableData2.every((v) => {
        return v.invoiceNo !== 0 && v.invoiceFile !== "" && v.invoiceNo != null && v.invoiceFile != null
      })
      console.log(arr);
      console.log(c);
      if (c) {
        console.log(this.tableData2);
        if(this.Send){
          arr.forEach((v)=>{
            v.billId=this.Send.id;
            v.billNo=this.Send.billNo;
          })
          getUpdata(
          {
            billDetails: arr,
            isDraft: data
          }
        ).then((res) => {
          this.$message.success(`提交成功`);
          this.hide()
          console.log(res);

        })
        }else{ 
          getUpdata(
          {
            billDetails: arr,
            isDraft: data
          }
        ).then((res) => {
          this.$message.success(`提交成功`);
          this.hide()
          console.log(res);

        }) 
        }
        
      }else{
        
        this.tableData.some((v)=>{
        if(v.invoiceNo==""||v.invoiceNo==null){
          return this.$message.error(`发票号未填写`);
        }else if(v.invoiceFile==""||v.invoiceFile==null){
          console.log(111);
          return this.$message.error(`发票附件未上传`);
        }
          
        })
      }

    },
    Staging(data) {
let arr=[]
console.log(this.tableData2);
      this.tableData.some((v, i) => {
        if(!v.deliveryCompanyName){
          v.deliveryCompanyName=v.companyName
          v.deliveryCompanyId=v.companyId

        }
        if (this.tableData2[0].invoiceNo == 0 || this.tableData2[0].invoiceFile == "" || this.tableData2[0].invoiceNo == null || this.tableData2[0].invoiceFile == null) {
        } else {
          if (v.invoiceNo == 0) {
            v.invoiceNo = this.tableData[i - 1].invoiceNo
            v.invoiceFile = this.tableData[i - 1].invoiceFile

          }
          arr.push({
            id:v.id ||null,
          orderId:v.orderId,
            batchId:v.batchId,
            batchName:v.batchName,
instId:v.instId,
instName:v.instName,
instNo:v.instNo,
medicineNo:v.medicineNo,
medicineName:v.medicineName,
categoryName:v.categoryName,
shotType:v.shotType,
specification:v.specification,
pack:v.pack,
purchaseAmount:v.purchaseAmount,
purchasePrice:v.purchasePrice,
purchaseFee:v.purchaseFee,
companyName:v.deliveryCompanyName,
companyId:v.deliveryCompanyId,
invoiceId:v.invoiceId,
invoiceNo:v.invoiceNo,
invoiceFile:v.invoiceFile,
instUser:v.instUser,
areaUser:v.areaUser,
paymentFile:v.paymentFile
          })
        }

      })
      console.log(arr);
      let c = this.tableData2.every((v) => {
        return v.invoiceNo !== 0 && v.invoiceFile !== "" && v.invoiceNo != null && v.invoiceFile != null
      })
      if (c) {
        if(this.Send){
         arr.map((v)=>{
          v.billNo=this.Send.billNo;
          v.billId=this.Send.id;
         })
          console.log(arr);
          getUpdata(
          {
            billDetails:arr,
            isDraft: data
          }
        ).then((res) => {
          this.$message.success(`暂存成功`);
          this.hide()
          console.log(res);

        })
        }else{
          getUpdata(
          {
            billDetails: arr,
            isDraft: data
          }
        ).then((res) => {
          this.$message.success(`暂存成功`);
          this.hide()
          console.log(res);

        })
        }
      }else{
         this.tableData.some((v)=>{
         if(v.invoiceNo==""||v.invoiceNo==null){

        console.log(121424);
          return this.$message.error(`发票号未填写`);
        }else if(v.invoiceFile==""||v.invoiceFile==null){
          console.log(111);
          return this.$message.error(`发票附件未上传`);
        }
          
        })
      }
      console.log(this.tableData);

    },
    instChange(data) {
      console.log(this.value3, data);
      if (!this.Send.instName) {
        this.instData.value = this.value3

        this.form.map((v) => {
          if (this.value3 == v.value) {
            this.instData.label = v.label
          }
          console.log(this.instData);
        })
      }

    },
    number() {
      this.priceSum = 0
      this.num = this.tableData.length
      this.tableData.map((v) => {
        if (v.purchaseFee === null) {
          v.purchaseFee = 0
        }
        this.priceSum += parseFloat(v.purchaseFee)
        return v
      })
    },
    changeDia(data) {
      this.dialogVisible = data
    },
    fileUrl() {
      return `/api/blade-resource/oss/endpoint/put-file?${this.website.tokenHeader}=${getToken()}`
    },
    changeData(data) {
      this.tableData1 = []
      let arr = []
      arr.unshift(...data)
      arr.forEach((item) => {
        if (!this.tableData.some(m => m.orderNo === item.orderNo && m.medicineName === item.medicineName&&m.medicineNo==item.medicineNo&&m.id===item.id)) {
          this.tableData1.unshift(item);
          this.tableData.unshift(item)
        }
        this.tableData2=this.tableData
        this.SIZE = this.tableData.length
        return this.tableData;
      })
      console.log(this.tableData, this.tableData2);
      this.number()
      this.changeTabel()
      console.log(data);
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
      this.changeTabel()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
      this.changeTabel()
    },
    handleDelete(ids) {
      if (this.Send.length != 0) {
        let choose = this.tableData1.every((v) => {
          if (v.id == ids) {
            return false
          } else {
            return true
          }
        })
        console.log(choose);
        if (choose) {
          if (this.tableData2.length == 1) {
            Fathremove(this.Send.id).then(() => {
              this.$message.success('删除成功');
this.getList()
              this.hide()
              this.number()
            })
          } else {
            remove(ids).then(() => {
              this.$message.success('删除成功');
              this.tableData2 = this.tableData.concat(this.tableData1)
              this.getList()
              this.number()
            });
          }
        } else {
          if (this.tableData2.length == 1) {
            Fathremove(this.Send.id).then(() => {
              this.$message.success('删除成功');
              this.tableData2 = this.tableData.concat(this.tableData1)
              this.hide()
              this.number()
            })
          } else {
              let arr = []
            this.tableData1.map((v, i) => {
              if (v.id == ids) {
                this.tableData1.splice(i, 1)
                this.$message.success('删除成功');
                arr.unshift(...this.tableData1);
                this.getList()
              }
              this.number()
            })
          }
        }

      } else {
        console.log(this.tableData1);
        this.tableData1.map((v, i) => {
          if (v.id == ids) {
          console.log(i);
            this.tableData1.splice(i, 1)
            this.$message.success('删除成功');
            console.log(this.tableData1);
            let arr = []
            arr.unshift(...this.tableData1)
            console.log(arr);
            this.tableData2 = arr
            console.log(this.tableData2);
          }
          this.number()
        })
      }




    },
    hide() {
      this.$emit("changeTwo", false)
    }
  }
}
</script>
  
<style lang="scss" scoped>
.df {
  display: flex;
  align-items: center;
}
::v-deep .el-alert{
  padding:4px 16px !important;
    }
    ::v-deep .el-alert__icon.is-big{
      font-size:22px !important;
    }
    ::v-deep .el-alert__description{
      margin:0

    }
.jcsb {
  justify-content: space-between;
}

.el-table {
  margin-bottom: 30px;
}

.ml {
  margin-left: 60px;
}

::v-deep th {
  background-color: #f1f1f1;
}

::v-deep .el-table__cell {
  height: 50px !important;
}

h2 {
  font-size: 18px;
}

.width {
  width: 120px;
  height: 36px;
}

.ret {
  margin-left: 30%;
  margin-right: 60px;
}

.number {
  font-size: 16px;
  color: #62c7f8;
}
::v-deep .el-alert--info .el-alert__description{
  color:#000!important;
  font-size: 14px;
}
::v-deep th.el-table__cell {
  background-color: #fafafa;
}

::v-deep .el-table__cell {
  border-right: 1px solid #EBEEF5 !important;
  text-align: center;
}

::v-deep .cell {
  display: flex;
  justify-content: center;
}
</style>